package com.bringspring.oauth.method.password.granter;

import com.bringspring.oauth.method.password.token.AccountPasswordAuthenticationToken;
import com.bringspring.oauth.method.qywechat.token.WeComAuthenticationToken;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.oauth2.provider.*;
import org.springframework.security.oauth2.provider.token.AbstractTokenGranter;
import org.springframework.security.oauth2.provider.token.AuthorizationServerTokenServices;

import java.util.Map;

public class AccountPasswordAbstractTokenGranter extends AbstractTokenGranter {

    private static final String GRANT_TYPE = "account";
    private final AuthenticationManager authenticationManager;
    public AccountPasswordAbstractTokenGranter(AuthenticationManager authenticationManager, AuthorizationServerTokenServices tokenServices, ClientDetailsService clientDetailsService, OAuth2RequestFactory requestFactory) {
        super(tokenServices, clientDetailsService, requestFactory, GRANT_TYPE);
        this.authenticationManager = authenticationManager;

    }
    protected OAuth2Authentication getOAuth2Authentication(ClientDetails client, TokenRequest tokenRequest) {
        Map<String, String> requestParameters = tokenRequest.getRequestParameters();
        String account = requestParameters.get("account");
        String password = requestParameters.get("password");
        AccountPasswordAuthenticationToken authenticationToken = new AccountPasswordAuthenticationToken(account,password);
        authenticationToken.setDetails(requestParameters);
        authenticationManager.authenticate(authenticationToken);
        OAuth2Request oAuth2Request = getRequestFactory().createOAuth2Request(client, tokenRequest);
        return new OAuth2Authentication(oAuth2Request,authenticationToken);
    }
}
